/* $RCSFile: StdAuxPage.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/StdAuxPage.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:29  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.IO;
using System.Configuration;
using System.Collections;
using System.Reflection;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Globalization;

using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Core;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Helpers;
using AddonNice.Security;
using AddonNice.Configuration;
using AddonNice.UI.DataTypes;


using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.UI
{
	/// <summary>
	/// StdAuxPage inherits from AddonNice.UI.CRMPage
    /// 
    /// 
	/// All portal 'complementary pages' must inherit from it: all pages opened by buttons in modules must inherit from this page or one of its children
    /// When this page object is created, portal has loaded the calling page settings from its pageId normally passed in the query string as PageId
    /// Module SettingsDic is also loaded from the calling Module, using the module id normally passed in the query string as ModId
    /// Doing so allow to read and change page and module settings.
    /// 
    /// All classes under this page support specific MasterPages that are loaded from DB using the site wide MasterPage setting or the Page specific one
    /// 
    /// This class also contains all the tools to use image buttons with skins that will be adapted to the UI Culture
    /// To do this we must set the skin in the OnPreInit handler.
    /// Due to .net logic, in the PreInit phase of the Page lifeCycle, items are not instanciated, so each children from this class has the responsability 
    /// to create one or 2 placeholders and to assign them to the placeHolderForButtons defined here.
    /// 
    /// 2008: ->Correction of this .Net problem of controls not being instanciated in OnPreInit: 
    /// it appears that controls are not instanciated in OnPreInit because the MasterPage is not instanciated, 
    /// if we set "MasterPage forceInstance= Mater; " on beginning of OnPreInit, controls are now available.
    /// So we have no reason to create the placeholders in child controls and have a virtual PlaceHolder method
    /// -> At that date code has not been corrected to adopt this feature
    /// 
    /// A Protected constructor allow to choose automatic creation of all necessary buttons
    /// 
    /// The class also provides users with handling for standards evens associated to buttons: Update, Delete, Flush, Custom Action
    /// Defining delegates which could be used to register specific handlers
	/// </summary>
	public class StdAuxPage : CRMPage
    {
        #region Flags to manage automatic Save/Save&Close/Cancel buttons
        
        protected bool PageHasDeleteBtn         =   false;
        protected bool PageHasUpdateBtn         =   true;
        protected bool PageHasCancelBtn         =   true;
        protected bool PageHasSaveAndCloseBtn   =   true;
        
        #endregion flags to manage automatic Save/SavandClose/Cancel/etc buttons

        #region security
		
        protected virtual bool UserLogged
		{
			get
			{
                AuthenticationMode md   =   Config.AuthenticationMode;
                bool strace             =   ( SecurityTraceSwitch.Sw.TraceVerbose || AuthenticationTrace.Sw.TraceVerbose );
                if ( strace )
                {
                    string info         =   SecurityTraceSwitch.Sw.Info;
                    if (AuthenticationTrace.Sw.TraceVerbose )
                        info            =   AuthenticationTrace.Sw.Info;
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage UserLogged GET BEG AuthenticationMode: {0}.",md),info);
                }
                bool ret                =   false;
                if ( md == AuthenticationMode.Forms)
				    ret                 =   HttpContext.Current.Request.IsAuthenticated;
                else if ( md == AuthenticationMode.Windows)
				    ret                 =   HttpContext.Current.Request.LogonUserIdentity.IsAuthenticated;
                if ( strace )
                {
                    string info         =   SecurityTraceSwitch.Sw.Info;
                    if (AuthenticationTrace.Sw.TraceVerbose )
                        info            =   AuthenticationTrace.Sw.Info;
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage UserLogged GET END ret: {0}.",ret),info);
                }
                return ret;
			}
		}
        #endregion security

        #region  Master Page definition

        /// <summary>
        /// Flag to indicate that masterpages are supported by this page.
        /// As we have no way to see if a page has the 'masterPage' infrastructure or not, we must use an internal flag
        /// When true the default site or page masterpage will be installed in MasterPageFile
        /// </summary>
        public virtual bool SupportMasterPage
        {
            get
            {
                return true;
            }
        }
        
        /// <summary>
        /// We force MasterPageFile from customMasterPage if exists or from portalSettings
        /// Value is get from value set in the aspx page, then from custom value for this page then from portal default values
        /// No reset fonction, always set for a non empty value
        /// DO NOT TRY TO SET the default masterPage in the get if not already installed because we could be after OnPreInit in page lifecycle
        /// </summary>
        public override string MasterPageFile
        {
            get
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( "[V]StdAuxPage MasterPageFile Get BEG.",PageTraceSwitch.Sw.Info);
                if (IsDesignMode)
                    return base.MasterPageFile;
                if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage MasterPageFile Get END base.MasterPageFile: [{0}].",base.MasterPageFile),PageTraceSwitch.Sw.Info);
                return base.MasterPageFile;

            }
            set
            {
                if ( MasterPageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage MasterPageFile SET SupportMasterPage: {0}, value: {1}", SupportMasterPage,value),MasterPageTraceSwitch.Sw.Info);
                if ( SupportMasterPage )
                    base.MasterPageFile = value;
            }
        }
        
        #endregion  Master Page definition

        #region DemoLabel to Signal any Suppressed fonction due to demo mode

        Label _SignalDemoLbl    =   null;

        public Label SignalDemoLbl
        {
			get
			{
                if ( PageTraceSwitch.Sw.TraceVerbose )
                   Trace2.WriteLine( "[V]StdAuxPage SignalDemoLbl GET.",PageTraceSwitch.Sw.Info);
				if ( _SignalDemoLbl != null )
					return _SignalDemoLbl;
				if ( IsDesignMode )
					return null;
				object ob	=	FindControl("MasterDemoLbl");
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage _SignalDemoLbl GET found: {0}", ob != null),PageTraceSwitch.Sw.Info);
                if (ob is Label)
                {
                    _SignalDemoLbl = (Label)ob;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( "[V]StdAuxPage SignalDemoLbl GET found .",PageTraceSwitch.Sw.Info);
                }
				else if (ob == null && Master != null )
				{
					ob	=	Master.FindControl("MasterDemoLbl");
					if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage SignalDemoLbl GET found in Master: {0}", ob != null),PageTraceSwitch.Sw.Info);
					if (ob is Label)
					{
						_SignalDemoLbl = (Label)ob;
						if ( PageTraceSwitch.Sw.TraceVerbose )
                            Trace2.WriteLine( "[V]StdAuxPage SignalDemoLbl GET found in Master.",PageTraceSwitch.Sw.Info);
					}
				}
                return _SignalDemoLbl;
			}
			set
			{
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage SignalDemoLbl SET.",PageTraceSwitch.Sw.Info);
                _SignalDemoLbl      =   value;
			}
		}

        void StdAuxPage_SignalDemo(object sender,ADNPageEventArgs e)
        {
            if ( SignalDemoLbl == null )
                return;
            SignalDemoLbl.Text  =  LocalizeHelper.Localize("DEMO_SUPPRESSED","Demo limited version");
        }

        
        #endregion DemoLabel to Signal any Suppressed fonction due to demo mode

        #region placeholders for automatic buttons management
        /// <summary>
		/// MUST be overriden on the child page with the exact placeholder
		/// When this placeHolder id declared in the Page it is autmatically filled with the standard buttons Update, Save and close, Delete, Cancel
		/// This property must be used in or after the onInit handler, Placeholders will not be found if called before
		/// </summary>
        private PlaceHolder _placeHolderForButtons = null;
        protected virtual PlaceHolder placeHolderForButtons
		{
			get
			{
                if ( PageTraceSwitch.Sw.TraceVerbose )
                   Trace2.WriteLine( "[V]StdAuxPage placeHolderForButtons GET.",PageTraceSwitch.Sw.Info);
				if ( _placeHolderForButtons != null )
					return _placeHolderForButtons;
				if ( IsDesignMode )
					return null;
				object ob	=	FindControl("PlaceHolderButtons");
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage placeHolderForButtons GET found={0}", ob != null),PageTraceSwitch.Sw.Info);
                if (ob is PlaceHolder)
                {
                    _placeHolderForButtons = (PlaceHolder)ob;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( "[V]StdAuxPage placeHolderForButtons GET found .",PageTraceSwitch.Sw.Info);
                }
				else if (ob == null && Master != null )
				{
					ob	=	Master.FindControl("PlaceHolderButtons");
					if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage placeHolderForButtons GET found in Master ={0}", ob != null),PageTraceSwitch.Sw.Info);
					if (ob is PlaceHolder)
					{
						_placeHolderForButtons = (PlaceHolder)ob;
						if ( PageTraceSwitch.Sw.TraceVerbose )
                            Trace2.WriteLine( "[V]StdAuxPage placeHolderForButtons GET found in Master.",PageTraceSwitch.Sw.Info);
					}
				}
                return _placeHolderForButtons;
			}
			set
			{
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage placeHolderForButtons SET.",PageTraceSwitch.Sw.Info);
                _placeHolderForButtons = value;
			}
		}


		/// <summary>
		/// MUST be overriden on the child page with the exact placeholder
		/// When this placeHolder id declared in the Page it is aumatically filled with the standard buttons Update, Save and close, Delete, Cancel
		/// This property must be used in or after the onInit handler, Placeholders will not be found if called before
		/// </summary>
        private PlaceHolder _placeHolderForButtons2 = null;
        protected virtual PlaceHolder placeHolderForButtons2
		{
			get
			{
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage placeHolderForButtons2 GET.",PageTraceSwitch.Sw.Info);
				if ( _placeHolderForButtons2 != null )
					return _placeHolderForButtons2;
				if ( IsDesignMode )
					return null;
				object ob	=	FindControl("PlaceHolderButtons2");
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage placeHolderForButtons2 GET found={0}", ob != null),PageTraceSwitch.Sw.Info);
                if (ob is PlaceHolder)
                {
                    _placeHolderForButtons2 = (PlaceHolder)ob;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]StdAuxPage placeHolderForButtons2 GET found .",PageTraceSwitch.Sw.Info);
                }
				else if (ob == null && Master != null )
				{
					ob	=	Master.FindControl("PlaceHolderButtons2");
					if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage placeHolderForButtons2 GET found in Master ={0}", ob != null),PageTraceSwitch.Sw.Info);
					if (ob is PlaceHolder)
					{
						_placeHolderForButtons2 = (PlaceHolder)ob;
						if ( PageTraceSwitch.Sw.TraceVerbose )
                            Trace2.WriteLine("[V]StdAuxPage placeHolderForButtons2 GET found in Master.",PageTraceSwitch.Sw.Info);
					}
				}
                return _placeHolderForButtons2;
			}
			set
			{
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage Set placeHolderForButtons2.",PageTraceSwitch.Sw.Info);
                _placeHolderForButtons2 = value;
			}
		}
        #endregion placeholders for automatic buttons management

        #region automatic buttons Management
        /// <summary>
		/// Standard update button
		/// This property must be used in or after the onInit handler, buttons will not be found if called before
		/// Standard Page buttons could also be assigned directly (set) to a value in the OnPreInit Handler, just for having there Skins recongnised by the Page's ModulesLayout handled at that time
		/// This is done in some inherited Page class like AddEditItem.
		/// </summary>
        private WebControl _updateButton = null;
        protected virtual WebControl updateButton
		{
			get
			{
				if ( _updateButton != null )
					return _updateButton;
				if ( IsDesignMode )
					return null;
				object ob	=	FindControl("updateBtn");
                if (ob is WebControl)
                {
                    _updateButton = (WebControl)ob;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]StdAuxPage Get found updateButton.",PageTraceSwitch.Sw.Info);
                }
                return _updateButton;
			}
			set
			{
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage Set updateButton.",PageTraceSwitch.Sw.Info);
                _updateButton = value;
                if ( string.IsNullOrEmpty(_updateButton.ID) )
                    _updateButton.ID    =   "updateBtn";
				if ( string.IsNullOrEmpty(value.SkinID))
					_updateButton.SkinID	=	"Update_"+LocalizeHelper.GetCurrentNeutralCultureName();
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage updateButton set SkinID: {0}.",_updateButton.SkinID),PageTraceSwitch.Sw.Info);
			}
		}

        private WebControl _updateButton2 = null;
        /// <summary>
        /// We often need 2 update buttons
		/// This property must be used in or after the onInit handler, buttons will not be found if called before
		/// Standard Page buttons could also be assigned directly (set) to a value in the OnPreInit Handler, just for having there Skins recongnised by the Page's ModulesLayout handled at that time
		/// This is done in some inherited Page class like AddEditItem.
        /// </summary>
        protected virtual WebControl updateButton2
        {
            get
            {
                if (_updateButton2 != null)
                    return _updateButton2;
                if (IsDesignMode)
                    return null;
                object ob = FindControl("updateBtn2");
                if (ob is WebControl)
                {
                    _updateButton2 = (WebControl)ob;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]StdAuxPage Get found updateButton2.",PageTraceSwitch.Sw.Info);
                }
                return _updateButton2;
            }
            set
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage Set updateButton2.",PageTraceSwitch.Sw.Info);
                _updateButton2 = value;
                if ( string.IsNullOrEmpty(_updateButton2.ID) )
                    _updateButton2.ID    =   "updateBtn2";
				if ( string.IsNullOrEmpty(value.SkinID))
					_updateButton2.SkinID	=	"Update_"+LocalizeHelper.GetCurrentNeutralCultureName();
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage updateButton2 set SkinID: {0}.",_updateButton2.SkinID),PageTraceSwitch.Sw.Info);
            }
        }

		/// <summary>
		/// Standard delete button
		/// This property must be used in or after the onInit handler, buttons will not be found if called before
		/// Standard Page buttons could also be assigned directly (set) to a value in the OnPreInit Handler, just for having there Skins recongnised by the Page's ModulesLayout handled at that time
		/// This is done in some inherited Page class like AddEditItem.
		/// </summary>
        private WebControl _deleteButton = null;
        protected virtual WebControl deleteButton
		{
			get
			{
				if ( _deleteButton != null )
					return _deleteButton;
				if ( IsDesignMode )
					return null;
				object ob	=	FindControl("deleteBtn");
                if (ob is WebControl)
                {
                    _deleteButton = (WebControl)ob;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]StdAuxPage Get found deleteButton.",PageTraceSwitch.Sw.Info);
                }
                return _deleteButton;
			}
			set
			{
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage Set deleteButton.",PageTraceSwitch.Sw.Info);
                _deleteButton = value;
                if ( string.IsNullOrEmpty(_deleteButton.ID) )
                    _deleteButton.ID    =   "deleteBtn";
				if ( string.IsNullOrEmpty(value.SkinID))
					_deleteButton.SkinID	=	"Delete_"+LocalizeHelper.GetCurrentNeutralCultureName();
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage delete set SkinID: {0}.",_deleteButton.SkinID),PageTraceSwitch.Sw.Info);
			}
		}

        private WebControl _deleteButton2 = null;
        /// <summary>
        /// Sometime we need 2 delete buttons
		/// This property must be used in or after the onInit handler, buttons will not be found if called before
		/// Standard Page buttons could also be assigned directly (set) to a value in the OnPreInit Handler, just for having there Skins recongnised by the Page's ModulesLayout handled at that time
		/// This is done in some inherited Page class like AddEditItem.
        /// </summary>
        protected virtual WebControl deleteButton2
        {
            get
            {
                if (_deleteButton2 != null)
                    return _deleteButton2;
                if (IsDesignMode)
                    return null;
                object ob = FindControl("deleteBtn2");
                if (ob is WebControl)
                {
                    _deleteButton2 = (WebControl)ob;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]StdAuxPage Get found deleteButton2.",PageTraceSwitch.Sw.Info);
                }
                return _deleteButton2;
            }
            set
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage Set deleteButton2.",PageTraceSwitch.Sw.Info);
                _deleteButton2 = value;
                if ( string.IsNullOrEmpty(_deleteButton2.ID) )
                    _deleteButton2.ID    =   "deleteBtn2";
				if ( string.IsNullOrEmpty(value.SkinID))
					_deleteButton2.SkinID	=	"Delete_"+LocalizeHelper.GetCurrentNeutralCultureName();
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage delete set SkinID: {0}.",_deleteButton2.SkinID),PageTraceSwitch.Sw.Info);
            }
        }

        /// <summary>
        /// Standard saveAndCloseButton button
		/// This property must be used in or after the onInit handler, buttons will not be found if called before
		/// Standard Page buttons could also be assigned directly (set) to a value in the OnPreInit Handler, just for having there Skins recongnised by the Page's ModulesLayout handled at that time
		/// This is done in some inherited Page class like AddEditItem.
        /// </summary>
        private WebControl _saveAndCloseButton = null;
        protected virtual WebControl saveAndCloseButton
        {
            get
            {
                if (_saveAndCloseButton != null)
                    return _saveAndCloseButton;
                if (IsDesignMode)
                    return null;
                object ob = FindControl("saveAndCloseBtn");
                if (ob is WebControl)
                {
                    _saveAndCloseButton = (WebControl)ob;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]StdAuxPage Get found saveAndCloseButton.",PageTraceSwitch.Sw.Info);
                }
                return _saveAndCloseButton;
            }
            set
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage Set saveAndCloseButton.",PageTraceSwitch.Sw.Info);
                _saveAndCloseButton = value;
                if ( string.IsNullOrEmpty(_saveAndCloseButton.ID) )
                    _saveAndCloseButton.ID    =   "saveAndCloseBtn";
				if ( string.IsNullOrEmpty(value.SkinID))
					_saveAndCloseButton .SkinID	=	"SaveAndClose_"+LocalizeHelper.GetCurrentNeutralCultureName();
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage saveAndCloseButton set SkinID: {0}.",_saveAndCloseButton.SkinID),PageTraceSwitch.Sw.Info);
            }
        }


        /// <summary>
        /// Standard saveAndCloseButton button 2
		/// This property must be used in or after the onInit handler, buttons will not be found if called before
		/// Standard Page buttons could also be assigned directly (set) to a value in the OnPreInit Handler, just for having there Skins recongnised by the Page's ModulesLayout handled at that time
		/// This is done in some inherited Page class like AddEditItem.
        /// </summary>
        private WebControl _saveAndCloseButton2 = null;
        protected virtual WebControl saveAndCloseButton2
        {
            get
            {
                if (_saveAndCloseButton2 != null)
                    return _saveAndCloseButton2;
                if (IsDesignMode)
                    return null;
                object ob = FindControl("saveAndCloseBtn2");
                if (ob is WebControl)
                {
                    _saveAndCloseButton2 = (WebControl)ob;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]StdAuxPage Get found saveAndCloseButton2.",PageTraceSwitch.Sw.Info);
                }
                return _saveAndCloseButton2;
            }
            set
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage Set saveAndCloseButton2.",PageTraceSwitch.Sw.Info);
                _saveAndCloseButton2 = value;
                if ( string.IsNullOrEmpty(_saveAndCloseButton2.ID) )
                    _saveAndCloseButton2.ID    =   "saveAndCloseBtn2";
				if ( string.IsNullOrEmpty(value.SkinID))
					_saveAndCloseButton2.SkinID	=	"SaveAndClose_"+LocalizeHelper.GetCurrentNeutralCultureName();
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage saveAndCloseButton2 set SkinID: {0}.",_saveAndCloseButton2.SkinID),PageTraceSwitch.Sw.Info);
            }
        }

        /// <summary>
        /// Standard adminPropertiesButton button
		/// This property must be used in or after the onInit handler, buttons will not be found if called before
		/// Standard Page buttons could also be assigned directly (set) to a value in the OnPreInit Handler, just for having there Skins recongnised by the Page's ModulesLayout handled at that time
		/// This is done in some inherited Page class like AddEditItem.
        /// </summary>
        private WebControl _adminPropertiesButton = null;
        protected virtual WebControl adminPropertiesButton
        {
            get
            {
                if (_adminPropertiesButton != null)
                    return _adminPropertiesButton;
                if (IsDesignMode)
                    return null;
                object ob = FindControl("adminPropertiesBtn");
                if (ob is WebControl)
                {
                    _adminPropertiesButton = (WebControl)ob;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]StdAuxPage Get found adminPropertiesButton.",PageTraceSwitch.Sw.Info);
                }
                return _adminPropertiesButton;
            }
            set
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage Set adminPropertiesButton.",PageTraceSwitch.Sw.Info);
                _adminPropertiesButton = value;
                if ( string.IsNullOrEmpty(_adminPropertiesButton.ID) )
                    _adminPropertiesButton.ID    =   "adminPropertiesBtn";
				if ( string.IsNullOrEmpty(value.SkinID))
					_adminPropertiesButton.SkinID	=	"ModuleParameters_"+LocalizeHelper.GetCurrentNeutralCultureName();
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage adminPropertiesButton set SkinID: {0}.",_adminPropertiesButton.SkinID),PageTraceSwitch.Sw.Info);
            }
        }

        /// <summary>
        /// Standard adminProperties Button button
		/// This property must be used in or after the onInit handler, buttons will not be found if called before
		/// Standard Page buttons could also be assigned directly (set) to a value in the OnPreInit Handler, just for having there Skins recongnised by the Page's ModulesLayout handled at that time
		/// This is done in some inherited Page class like AddEditItem.
        /// </summary>
        private WebControl _adminPropertiesButton2 = null;
        protected virtual WebControl adminPropertiesButton2
        {
            get
            {
                if (_adminPropertiesButton2 != null)
                    return _adminPropertiesButton2;
                if (IsDesignMode)
                    return null;
                object ob = FindControl("adminPropertiesBtn2");
                if (ob is WebControl)
                {
                    _adminPropertiesButton2 = (WebControl)ob;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]StdAuxPage Get found adminPropertiesButton2.",PageTraceSwitch.Sw.Info);
                }
                return _adminPropertiesButton2;
            }
            set
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage Set adminPropertiesButton2.",PageTraceSwitch.Sw.Info);
                _adminPropertiesButton2 = value;
                if ( string.IsNullOrEmpty(_adminPropertiesButton2.ID) )
                    _adminPropertiesButton2.ID    =   "adminPropertiesBtn2";
				if ( string.IsNullOrEmpty(value.SkinID))
					_adminPropertiesButton2.SkinID	=	"ModuleParameters_"+LocalizeHelper.GetCurrentNeutralCultureName();
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage adminPropertiesButton2 set SkinID: {0}.",_adminPropertiesButton2.SkinID),PageTraceSwitch.Sw.Info);
            }
        }

        /// <summary>
		/// Standard cancel button
		/// This property must be used in or after the onInit handler, buttons will not be found if called before
		/// Standard Page buttons could also be assigned directly (set) to a value in the OnPreInit Handler, just for having there Skins recongnised by the Page's ModulesLayout handled at that time
		/// This is done in some inherited Page class like AddEditItem.
		/// </summary>
        private WebControl _cancelButton = null;
        protected virtual WebControl cancelButton
		{
			get
			{
				if ( _cancelButton != null )
					return _cancelButton;
				if ( IsDesignMode )
					return null;
				object ob	=	FindControl("cancelBtn");
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage Get cancelButton is null: {0}.", (ob== null)),PageTraceSwitch.Sw.Info);
                if (ob == null && Master != null)
                {
                    ob = Master.FindControl("cancelBtn");
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage Get cancelButton in Master is null: {0}.", (ob == null)),PageTraceSwitch.Sw.Info);
                }
                if (ob is WebControl)
                {
                    _cancelButton = (WebControl)ob;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]StdAuxPage Get found cancelButton.",PageTraceSwitch.Sw.Info);
                }
                return _cancelButton;
			}
			set
			{
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage Set cancelButton.",PageTraceSwitch.Sw.Info);
                _cancelButton = value;
                if ( string.IsNullOrEmpty(_cancelButton.ID) )
                    _cancelButton.ID    =   "cancelBtn";
				if ( string.IsNullOrEmpty(value.SkinID))
					_cancelButton.SkinID	=	"Cancel_"+LocalizeHelper.GetCurrentNeutralCultureName();
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage cancelButton set SkinID: {0}.",_cancelButton.SkinID),PageTraceSwitch.Sw.Info);
				}
		}

        private WebControl _cancelButton2 = null;
        /// <summary>
        /// We often need 2 cancel buttons/page
		/// This property must be used in or after the onInit handler, buttons will not be found if called before
		/// Standard Page buttons could also be assigned directly (set) to a value in the OnPreInit Handler, just for having there Skins recongnised by the Page's ModulesLayout handled at that time
		/// This is done in some inherited Page class like AddEditItem.
        /// </summary>
        protected virtual WebControl cancelButton2
        {
            get
            {
                if (_cancelButton2 != null)
                    return _cancelButton2;
                if (IsDesignMode)
                    return null;
                object ob = FindControl("cancelBtn2");
                if (ob is WebControl)
                {
                    _cancelButton2 = (WebControl)ob;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]StdAuxPage Get found cancelButton2.",PageTraceSwitch.Sw.Info);
                }
                return _cancelButton2;
            }
            set
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage Set cancelButton2.",PageTraceSwitch.Sw.Info);
                _cancelButton2 = value;
                if ( string.IsNullOrEmpty(_cancelButton2.ID) )
                    _cancelButton2.ID    =   "cancelBtn2";
				if ( string.IsNullOrEmpty(value.SkinID))
					_cancelButton2.SkinID	=	"Cancel_"+LocalizeHelper.GetCurrentNeutralCultureName();
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage cancelButton2 set SkinID: {0}.",_cancelButton2.SkinID),PageTraceSwitch.Sw.Info);
            }
        }


        string _CustomBtnName      =    "CustomBtn";
        /// <summary>
        /// Used to set the custom button name for the Page
        /// For exemple when you have a button nammed ResetBtn set CustomBtnName = "ResetBtn"; in Init method 
        /// </summary>
        protected virtual string CustomBtnName
        {
            get
            {
                return _CustomBtnName;
            }
            set
            {
                _CustomBtnName =   value;
            }
        }

        /// <summary>
		/// Standard Custom button
		/// This property must be used in or after the onInit handler, buttons will not be found if called before
		/// Standard Page buttons could also be assigned directly (set) to a value in the OnPreInit Handler, just for having there Skins recongnised by the Page's ModulesLayout handled at that time
		/// This is done in some inherited Page class like AddEditItem.
		/// </summary>
        private WebControl _customButton = null;
        protected virtual WebControl customButton
		{
			get
			{
				if ( _customButton != null )
					return _customButton;
				if ( IsDesignMode )
					return null;
				object ob	=	FindControl(CustomBtnName);
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage Get customButton is null: {0}.", (ob== null)),PageTraceSwitch.Sw.Info);
                if (ob == null && Master != null)
                {
                    ob = Master.FindControl(CustomBtnName);
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage Get customButton in Master is null: {0}.", (ob == null)),PageTraceSwitch.Sw.Info);
                }
                if (ob is WebControl)
                {
                    _customButton = (WebControl)ob;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]StdAuxPage Get found customButton.",PageTraceSwitch.Sw.Info);
                }
                return _customButton;
			}
			set
			{
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage Set customButton.",PageTraceSwitch.Sw.Info);
                _customButton   = value;
                if ( string.IsNullOrEmpty(_customButton.ID) )
                    _customButton.ID    =   CustomBtnName;
				if ( string.IsNullOrEmpty(value.SkinID))
					_customButton.SkinID	=   CustomBtnName+"_"+LocalizeHelper.GetCurrentNeutralCultureName();
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage customButton set SkinID: {0}.",_customButton.SkinID),PageTraceSwitch.Sw.Info);
				}
		}

        private WebControl _customButton2 = null;
        protected virtual WebControl customButton2
		{
			get
			{
				if ( _customButton2 != null )
					return _customButton2;
				if ( IsDesignMode )
					return null;
				object ob	=	FindControl(CustomBtnName+"2");
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage Get customButton2 is null: {0}.", (ob== null)),PageTraceSwitch.Sw.Info);
                if (ob == null && Master != null)
                {

                    ob = Master.FindControl(CustomBtnName+"2");
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage Get customButton2 in Master is null: {0}.", (ob == null)),PageTraceSwitch.Sw.Info);
                }
                if (ob is WebControl)
                {
                    _customButton2 = (WebControl)ob;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]StdAuxPage Get found customButton2.",PageTraceSwitch.Sw.Info);
                }
                return _customButton2;
			}
			set
			{
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage Set customButton2.",PageTraceSwitch.Sw.Info);
                _customButton2   = value;
                if ( string.IsNullOrEmpty(_customButton2.ID) )
                    _customButton2.ID    =   CustomBtnName+"2";
				if ( string.IsNullOrEmpty(value.SkinID))
					_customButton2.SkinID	=   CustomBtnName+"_"+LocalizeHelper.GetCurrentNeutralCultureName();
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage customButton2 set SkinID: {0}.",_customButton2.SkinID),PageTraceSwitch.Sw.Info);
				}
		}

        #endregion automatic buttons

        #region Editors
        
        public IHtmlEditor GetEditor(PlaceHolder PlaceHolderHTMLEditor)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage GetEditor BEG PageID: {0}", PageID),PageTraceSwitch.Sw.Info);
            HtmlEditorDataType h = new HtmlEditorDataType();
            return h.GetEditor(PlaceHolderHTMLEditor, this);
        }

        #endregion Editors

        #region Events
        /// <summary>
        /// SaveAndClose Button click
        /// </summary>
        private void SaveAndCloseBtn_Click(object sender, System.EventArgs e)
        {
            SaveAndCloseClick(sender, new ADNPageEventArgs(ADNPageEventArgs.PgEventType.SaveAndClose,e));
        }

		/// <summary>
        /// Handler used whern standard buttons are ImageButtons
		/// </summary>
		private void SaveAndCloseImgBtn_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            SaveAndCloseClick(sender,new ADNPageEventArgs(ADNPageEventArgs.PgEventType.SaveAndClose,e));
        }

        private void SaveAndCloseClick(object sender, ADNPageEventArgs e)
        {
            Validate();
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage SaveAndCloseBtn_Click IsValid: {0}",IsValid),PageTraceSwitch.Sw.Info);
            if (!IsValid)
                return;
            OnUpdate(e);
            if (!e.Cancel && e.RedirectOnSuccess)
            {
                string redirectUrl  =   ReturnUrl;
                if ( redirectUrl == string.Empty )
                    redirectUrl =   HttpUrlBuilder.BuildUrl(PageID);
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage SaveAndCloseClick redirectUrl: '{0}'",redirectUrl),PageTraceSwitch.Sw.Info);
                Redirect(redirectUrl,true);
            }
        }    

        /// <summary>
        /// adminProperties Button click
        /// </summary>
        private void adminPropertiesBtn_Click(object sender, EventArgs e)
        {
            adminPropertiesClick(sender,new ADNPageEventArgs(ADNPageEventArgs.PgEventType.AdminProp,e));
        }

		/// <summary>
        /// adminProperties Button click
        /// Handler used whern standard buttons are ImageButtons
		/// </summary>
		private void adminPropertiesImgBtn_Click(object sender, ImageClickEventArgs e)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage adminPropertiesImgBtn_Click BEG sender: {0}",sender),PageTraceSwitch.Sw.Info);
            adminPropertiesClick(sender,new ADNPageEventArgs(ADNPageEventArgs.PgEventType.AdminProp,e));
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]StdAuxPage adminPropertiesImgBtn_Click END.",PageTraceSwitch.Sw.Info);
        }

        private void adminPropertiesClick(object sender, ADNPageEventArgs e)
        {
            Validate();
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage adminPropertiesClick IsValid: {0}",IsValid),PageTraceSwitch.Sw.Info);
            if (!IsValid)
                return;
            OnAdminProperties(e);
        }    

        /// <summary>
		/// Cancel Button click
		/// </summary>
        protected void CancelBtn_Click(Object sender, EventArgs e)
        {
            CancelBtnClick(sender,new ADNPageEventArgs(ADNPageEventArgs.PgEventType.Cancel,e));
        }

        /// <summary>
        /// Handler used whern standard buttons are ImageButtons
        /// </summary>
		protected void CancelImgBtn_Click(Object sender, System.Web.UI.ImageClickEventArgs e)
        {
            CancelBtnClick(sender,new ADNPageEventArgs(ADNPageEventArgs.PgEventType.Cancel,e));
        }
        
        protected void CancelBtnClick(Object sender, ADNPageEventArgs e) 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]StdAuxPage CancelBtn_Click.",PageTraceSwitch.Sw.Info);
            OnCancel(e);
		}
        
		/// <summary>
		/// Update Button click
		/// </summary>
        protected void UpdateBtn_Click(Object sender, EventArgs e)
        {
            UpdateBtnClick(sender,new ADNPageEventArgs(ADNPageEventArgs.PgEventType.Update,e));
        }
        
        /// <summary>
        /// Handler used when standard buttons are ImageButtons
        /// </summary>
		protected void UpdateImgBtn_Click(Object sender, System.Web.UI.ImageClickEventArgs e)
        {
            UpdateBtnClick(sender,new ADNPageEventArgs(ADNPageEventArgs.PgEventType.Update,e));
        }

		protected void UpdateBtnClick(Object sender, ADNPageEventArgs e) 
		{
			Validate();
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage UpdateBtn_Click IsValid: {0}",IsValid),PageTraceSwitch.Sw.Info);
            if (!IsValid)
                return;
            OnUpdate(e);
		}
        
		/// <summary>
		/// Delete Button Click
		/// </summary>
        protected void DeleteBtn_Click(Object sender, EventArgs e)
        {
            DeleteBtnClick(sender,new ADNPageEventArgs(ADNPageEventArgs.PgEventType.Delete,e));
        }
        /// <summary>
        /// Handler used whern standard buttons are ImageButtons
        /// </summary>
		protected void DeleteImgBtn_Click(Object sender, System.Web.UI.ImageClickEventArgs e)
        {
            DeleteBtnClick(sender, e);
        }
        protected void DeleteBtnClick(Object sender, EventArgs e) 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]StdAuxPage DeleteBtn_Click.",PageTraceSwitch.Sw.Info);
            OnDelete(new ADNPageEventArgs(ADNPageEventArgs.PgEventType.Delete,e));
		}

		/// <summary>
		/// Custom Button Click
		/// </summary>
        protected void CustomBtn_Click(Object sender, EventArgs e)
        {
            CustomBtnClick(sender,new ADNPageEventArgs(ADNPageEventArgs.PgEventType.Custom,e));
        }
        /// <summary>
        /// Handler for Custom button used whern standard buttons are ImageButtons
        /// </summary>
		protected void CustomImgBtn_Click(Object sender, ImageClickEventArgs e)
        {
            CustomBtnClick(sender, new ADNPageEventArgs(ADNPageEventArgs.PgEventType.Custom,e));
        }
        protected void CustomBtnClick(Object sender, ADNPageEventArgs e) 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]StdAuxPage CustomBtnClick.",PageTraceSwitch.Sw.Info);
            OnCustomAction(e);
        }
        #endregion Events

        #region events handlers

		public event PageEventHandler SignalDemo;
        /// <summary>
		/// Used to signal a Demo version when any handler is refused due to demo
		/// </summary>
        protected virtual void OnSignalDemo(ADNPageEventArgs e) 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnSignalDemo BEG SignalDemo!=null: {0}.",(SignalDemo != null)),PageTraceSwitch.Sw.Info);
            if ( SignalDemo != null )
            {
                SignalDemo(this,e);
            }
        }

        /// <summary>
		/// The Add event is defined using the event keyword.
		/// The type of Add is EventHandler.
		/// </summary>
		public event PageEventHandler Add;

		/// <summary>
		/// Handles OnAdd event at Page level<br/>
		/// Performs OnAdd actions that are common to all Pages<br/>
		/// Can be overridden
		/// </summary>
		protected virtual void OnAdd(ADNPageEventArgs e) 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnAdd Title : {0}", PageTitle),PageTraceSwitch.Sw.Info);
            // Demo version no Add
            if (IsDemo && !e.OverrideDemo )
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage OnAdd Demo version.",PageTraceSwitch.Sw.Info);
                OnSignalDemo(e); 
                return;
            }
            // Verify that the current user has access to edit this module
            // if not in a CRM iFrame, only Administrator may edit the page
            if ((IsUnderCRM && (string.IsNullOrEmpty(EntityName) || !PortalSecurity.HasAddPermissions(EntityName)))
                || (!IsUnderCRM && !PortalSecurity.IsUserInRoles(Config.CRMAdminRole)))
                    PortalSecurity.AccessDeniedEdit();

            if (Add != null) 
				Add(this, e); //Invokes the delegates

			//Flush cache
            if ( !e.Cancel && e.FlushCache )
			    OnFlushCache();
		}

		/// <summary>
		/// This is an internal update event, class that inherits from ADNPage have not to define this
        /// they should define 
		/// </summary>
		public event PageEventHandler Update;

		/// <summary>
		/// Handles OnUpdate event at Page level<br/>
		/// Performs OnUpdate actions that are common to all Pages<br/>
		/// Can be overridden
		/// This is an internal update event, class that inherits from ADNPage have not to define this
        /// they should add their handler the update eventhandler
		/// </summary>
		protected virtual void OnUpdate(ADNPageEventArgs e) 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnUpdate Title : {0}, RequestEntityTypename: {1}, EntityName: {2}.",
                    PageTitle,RequestEntityTypename,EntityName),PageTraceSwitch.Sw.Info);
            // Demo version no update
            if (IsDemo && !e.OverrideDemo )
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage OnUpdate Demo version.",PageTraceSwitch.Sw.Info);
                OnSignalDemo(e); 
                return;
            }
            // Verify that the current user has access to edit this module
            // if not in a CRM iFrame, only Administrator may edit the page
            if ( IsUnderCRM && 
                ( (string.IsNullOrEmpty(RequestEntityTypename) && (string.IsNullOrEmpty(EntityName))  )
                || ( !string.IsNullOrEmpty(RequestEntityTypename) && !PortalSecurity.HasAddPermissions(RequestEntityTypename )&& !PortalSecurity.HasUpdatePermissions(RequestEntityTypename ))
                || ( !string.IsNullOrEmpty(EntityName) && !PortalSecurity.HasAddPermissions(EntityName )&& !PortalSecurity.HasUpdatePermissions(EntityName) ) ) )
                PortalSecurity.AccessDeniedEdit();
            // Verify that the current user has access to update this entity
            // if not in a CRM iFrame, Administrator and special roles may edit the page
            // else if an entity has been assigned to this page, we check directly on the entity
            // else we check for all the modules and if we are ok to edit or add to any of them, its ok
            if ( !IsUnderCRM )
            {
                if ( !PortalSecurity.IsUserInRoles(Config.CRMAdminRole) )
                {
                    if ( string.IsNullOrEmpty(EntityName) )
                    {
                        bool Ok     =   true;
                        if ( PageTraceSwitch.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnUpdate LoadedModules.Count: {0}.",LoadedModules.Count),PageTraceSwitch.Sw.Info);
                        foreach ( PortalModuleControl md in LoadedModules.Values )
                        {
                            if ( PageTraceSwitch.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnUpdate LoadedModules.md.TitleText: {0}.",md.TitleText),PageTraceSwitch.Sw.Info);
                            Ok      =   PortalSecurity.IsUserInRoles(md.ModuleBaseConfiguration.AuthorizedEditRoles) ||
                                        PortalSecurity.IsUserInRoles(md.ModuleBaseConfiguration.AuthorizedAddRoles);
                            if ( !Ok )
                            {
                                if ( PageTraceSwitch.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnUpdate Not Ok for md.TitleText: {0}.",md.TitleText),PageTraceSwitch.Sw.Info);
                                PortalSecurity.AccessDeniedEdit();
                            }
                        }
                    }
                    else if ( !PortalSecurity.HasAddPermissions(EntityName) && !PortalSecurity.HasUpdatePermissions(EntityName) )
                        PortalSecurity.AccessDeniedEdit();
                }
            }

            if (Update != null) 
				Update(this, e); //Invokes the delegates
            if (!e.Cancel)
            {
                //Flush cache
                if (e.FlushCache)
                    OnFlushCache();
            }
		}


		/// <summary>
		/// The AdminProperties event is defined using the event keyword.
		/// The type of Update is EventHandler.
		/// </summary>
		public event PageEventHandler AdminProperties;

		
		/// <summary>
		/// Handles OnAdminProperties event at Page level<br/>
		/// Performs OnAdminProperties actions that are common to all Pages<br/>
		/// Can be overridden
		/// </summary>
		protected virtual void OnAdminProperties(ADNPageEventArgs e) 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnAdminProperties Title : {0}", PageTitle),PageTraceSwitch.Sw.Info);
            // Demo version no acces on properties
            if (IsDemo && !e.OverrideDemo )
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage OnAdminProperties Demo version.",PageTraceSwitch.Sw.Info);
                OnSignalDemo(e); 
                return;
            }
            // Verify that the current user has access to edit this module
            // if not in a CRM iFrame, only Administrator may edit the page
            if ( !PortalSecurity.IsUserInRoles(Config.CRMAdminRole) && 
                (( IsUnderCRM && (string.IsNullOrEmpty(EntityName) || !PortalSecurity.HasPropertiesPermissions(EntityName)) )
                || ( !IsUnderCRM ) ))
                PortalSecurity.AccessDeniedEdit();

            if (AdminProperties != null) 
				AdminProperties(this, e); //Invokes the delegates
			//Flush cache
            if ( e.FlushCache && !e.Cancel  )
    			OnFlushCache();
		}

		/// <summary>
		/// The FlushCache event is defined using the event keyword.
		/// The type of FlushCache is EventHandler.
		/// </summary>
		public event EventHandler FlushCache;

		/// <summary>
		/// Handles FlushCache event at Page level
		/// Performs FlushCache actions that are common to all Pages
		/// Can be overridden
		/// </summary>
		protected virtual void OnFlushCache() 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnFlushCache Title : {0}", PageTitle),PageTraceSwitch.Sw.Info);
            if (FlushCache != null) 
				FlushCache(this, new EventArgs()); //Invokes the delegates

			// remove module output from cache, if it's there
			StringBuilder sb    =   new StringBuilder();
            sb.AppendFormat("adn_{0}_mid{1}[{2}+{3}+{4}]", 
                new object[] { portalSettings.BaseAlias.ToLower(), 
                    ModuleID, 
                    portalSettings.PortalContentLanguage, 
                    portalSettings.PortalUILanguage, 
                    portalSettings.PortalDataFormattingCulture });
            string str          =   sb.ToString();
			if (Context.Cache[str] != null) 
				Context.Cache.Remove(str);
		}

		/// <summary>
		/// The Delete event is defined using the event keyword.
		/// The type of Delete is EventHandler.
		/// </summary>
		public event PageEventHandler Delete;

		/// <summary>
		/// Handles OnDelete event at Page level<br/>
		/// Performs OnDelete actions that are common to all Pages<br/>
		/// Can be overridden
		/// </summary>
		protected virtual void OnDelete(ADNPageEventArgs e) 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnDelete Type : {0}, IsUnderCRM: {1}, isDemo: {2}.", GetType(),IsUnderCRM,IsDemo),PageTraceSwitch.Sw.Info);
            // Demo version no delete
            if (IsDemo && !e.OverrideDemo )
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage OnDelete Demo version.",PageTraceSwitch.Sw.Info);
                OnSignalDemo(e); 
                return;
            }
            // Verify that the current user has access to delete in this item
            if ( IsUnderCRM )
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnDelete RequestEntityTypename: {0}.", RequestEntityTypename),PageTraceSwitch.Sw.Info);
                if ( ( string.IsNullOrEmpty(RequestEntityTypename) || !PortalSecurity.HasDeletePermissions(RequestEntityTypename) ) )
                    PortalSecurity.AccessDeniedEdit();
            }
            else
            {
                bool isAdm     =    PortalSecurity.IsUserInRoles(Config.CRMAdminRole);
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnDelete isAdmin: {0}.", isAdm),PageTraceSwitch.Sw.Info);
                // Admin delete without any right check
                if ( !isAdm )
                {
                    // Should we check isAttached ? quite uneasy for generic pages isAAttached should be keept empty, else it should contain the good entity ???
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnDelete IsAttached: {0}.", IsAttached),PageTraceSwitch.Sw.Info);
                    if ( IsAttached )
                    {
                        if ( PageTraceSwitch.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnDelete EntityName: {0}.", EntityName),PageTraceSwitch.Sw.Info);
                        if ( ( string.IsNullOrEmpty(EntityName) || !PortalSecurity.HasDeletePermissions(EntityName) ) )
                            PortalSecurity.AccessDeniedEdit();
                    }
                    else
                    {
                        bool modIsNul   =    ( Module == null );
                        if ( PageTraceSwitch.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnDelete modIsNul: {0}.", modIsNul),PageTraceSwitch.Sw.Info);
                        // Let see right on calling module if exist
                        if ( modIsNul ) 
                            PortalSecurity.AccessDeniedEdit();
                        if ( PageTraceSwitch.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnDelete Module.AuthorizedDeleteRoles: {0}.", Module.AuthorizedDeleteRoles),PageTraceSwitch.Sw.Info);
                        if ( !PortalSecurity.IsUserInRoles(Module.AuthorizedDeleteRoles) )
                            PortalSecurity.AccessDeniedEdit();
                    }
                }
            }

            if (Delete != null) 
				Delete(this, e); //Invokes the delegates

            if (!e.Cancel)
            {
                //Flush cache
                if (e.FlushCache)
                    OnFlushCache();
                // Redirect back to the calling page
                if (e.RedirectOnSuccess)
                    RedirectBackToReferringPage();
            }
		}

		/// <summary>
		/// The Cancel event is defined using the event keyword.
		/// The type of Cancel is EventHandler.
		/// </summary>
		public event EventHandler Cancel;

		protected virtual void OnCancel()
		{
            OnCancel(new EventArgs());
		}

		/// <summary>
		/// Handles OnCancel Event at Page level<br/>
		/// Performs OnCancel actions that are common to all Pages<br/>
		/// Can be overridden
		/// </summary>
		protected virtual void OnCancel(EventArgs e) 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnCancel Title : {0}", PageTitle),PageTraceSwitch.Sw.Info);
            if (Cancel != null) 
				Cancel(this, e); //Invokes the delegates
			// any other code goes here
			RedirectBackToReferringPage();
		}

		/// <summary>
		/// The CustomAction event is defined using the event keyword.
		/// The type of CustomAction is EventHandler.
		/// </summary>
		public event PageEventHandler CustomAction;
        
        /// <summary>
		/// Handles OnCustomAction event at Page level<br/>
		/// Performs OnCustomAction actions that are common to all Pages<br/>
		/// Can be overridden
		/// </summary>
		protected virtual void OnCustomAction(ADNPageEventArgs e) 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnCustomAction Title : {0}", PageTitle),PageTraceSwitch.Sw.Info);
            // Demo version no action
            if (IsDemo && !e.OverrideDemo )
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]StdAuxPage OnCustomAction Demo version.",PageTraceSwitch.Sw.Info);
                OnSignalDemo(e); 
                return;
            }

            if ( CustomAction != null) 
				CustomAction(this, e); //Invokes the delegates
            if (!e.Cancel)
            {
                //Flush cache
                if (e.FlushCache)
                    OnFlushCache();
                // Redirect back to the calling page
                if (e.RedirectOnSuccess)
                    RedirectBackToReferringPage();
            }
		}

        
        #endregion

        #region Properties (local)

        public virtual bool HasGoogleTranslator
        {
            get
            {
                if ( moduleSettingsDic.ContainsKey(StStr.GoogleTranslate) )
                    return ( portalSettings.CustomSettings[StStr.SiteSettingsGoogleTranslate].ToBool() && moduleSettingsDic[StStr.GoogleTranslate].ToBool() );
                return false;
            }
        }

        #endregion Properties (local)

        #region Properties (Modules)
        private int _moduleID = StStr.ModuleIDNotAssigned;
        /// <summary>
        /// This is the moduleID of the module that has called this page with ADD DEL or other command
		/// This string is extracted from the request parameter 'Mid'
		/// If no request parameter, moduleID is StStr.ModuleIDNotAssigned (zero)
		/// </summary>
        public int ModuleID
        {
            get
            {
                if (_moduleID == StStr.ModuleIDNotAssigned )
                {
                    // Determine ModuleID if specified
                    if (!IsDesignMode)
                    {
                        string str      =   Request.Params[StStr.strModuleID];
                        if (!string.IsNullOrEmpty(str))
                        {
                            try
                            {
                                _moduleID = Int32.Parse(str);
                            }
                            catch(Exception ex) 
                            {
                                if (PageTraceSwitch.Sw.TraceError)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]StdAuxPage ModuleID GET Parse str: {0}, ex : {1}", str, ex),PageTraceSwitch.Sw.Info);
                            }
                            if (PageTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage ModuleID GET PageID: {0}, _moduleID: '{1}'", PageID, _moduleID),PageTraceSwitch.Sw.Info);
                        }
                    }
                }
                return _moduleID;
            }
        }

        private ModuleConfiguration _module;
		/// <summary>
		/// This module is the one that called this page See ModuleID for detail
		/// If moduleID is zero module is unknown and null
		/// </summary>
		public ModuleConfiguration Module
		{
			get
			{
				if(_module == null)
				{
                    int modId =   ModuleID;
					if ( modId > StStr.ModuleIDNotAssigned )
					{
						// Obtain selected module data from current page if any page loaded
						foreach (ModuleConfiguration _mod in portalSettings.ActivePageSettings.Modules) 
						{
							if (_mod.ModuleID == modId )
							{
								_module = _mod;
								break;
							}
						}
                        // not loaded, take it directly from db or cache
                        if (_module == null)
                        {
                            _module  =   new ModuleConfiguration(modId);
                        }
					}					
				}
				return _module;
			}
		}

        private ModuleSettingsDictionary _moduleSettingsDic;
		/// <summary>
		/// Module settings of the module that called this page
		/// if no module identified, an empty settings dictionary is returned
		/// See ModuleID for details.
		/// </summary>
        public ModuleSettingsDictionary moduleSettingsDic
		{
			get
			{
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage moduleSettingsDic GET BEG is null: {0}.", _moduleSettingsDic == null ),PageTraceSwitch.Sw.Info);
				if( _moduleSettingsDic == null )
				{
					if (  ModuleID > StStr.ModuleIDNotAssigned )
						// Get settings from the database
						_moduleSettingsDic = ModuleSettingsDictionary.GetModuleSettings(ModuleID, this);
					else
                        // Or provides an empty SettingsDictionary 
						_moduleSettingsDic = new ModuleSettingsDictionary();
				}
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage moduleSettingsDic GET END Count: {0}, ModuleID: '{1}'", _moduleSettingsDic.Count, ModuleID),PageTraceSwitch.Sw.Info);
				return _moduleSettingsDic;
			}
		}
		#endregion

        #region Properties (Items)
		private int _itemID = -1;

		/// <summary>
		/// This is the item id that was selected on the module that called the property page
		/// Value come from the request paremeter named ItemID.
		/// If no corresponding request parameter, value is -1.
		/// </summary>
		public int ItemID
		{
			get
			{
				if (_itemID == -1)
				{
					// Determine ItemID if specified
					if (!IsDesignMode)
					{
						string str	    =	Request.Params[StStr.strItemID];
						if ( !string.IsNullOrEmpty(str) )
						{
							try
							{
								_itemID =   Int32.Parse(str);
							}
							catch(Exception ex)
							{
								if (PageTraceSwitch.Sw.TraceError)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]StdAuxPage ItemID Parse failed for ItemID: '{0}', ex : {1}",str,ex),PageTraceSwitch.Sw.Info);
							}
						}
					}
				}
				return _itemID;
			}	
			set
			{
				_itemID                 =   value;
			}
		}

		/// <summary>
		/// Used by Edit/Add Pages
		/// Check if we are creating a new item, true if  ItemID is (-1), the default value
		/// ItemID is set by query string "ItemID"
		/// </summary>
		public virtual bool isNewItem
		{
			get
			{
				return ((ItemID == -1) && !isCrmItem );
			}
		}

		public virtual bool isCrmItem
		{
			get
			{
				return (ItemCrmID != Guid.Empty );
			}
		}

        #endregion

        #region overrides from ADNPage
        
        /// <summary>
        /// Send in the Init Phase by ADNPage
		/// If a module exist, set it as current Module in Portal
		/// </summary>
		protected override void LoadSettings()
		{
            PortalSettings.TheActiveModule = ModuleID;
            base.LoadSettings();
        }

		/// Get the AllowedModules array from page if exists and set the restrictions for use
		/// For this method work, the user page need override AllowedModules with GUIDS
		/// </summary>
		protected override void ModuleGuidInCookie () 
		{
			if ( AllowedModules != null ) 
			{
				string guidsInUse	=	string.Empty;
				if ( Request.Cookies[StStr.strSecurityCookieName] != null )
				{
					guidsInUse		=	Request.Cookies[StStr.strSecurityCookieName].Value;
				}
				foreach (string mg in AllowedModules) 
				{
					if ( guidsInUse.IndexOf(mg.ToUpper()) > -1 ) 
                        return;
				}
				int aModuleID		=	ModuleID;
				if ( aModuleID > 0 )
				{
					guidsInUse		= new ModulesDB().GetModuleGuid(aModuleID).ToString().ToUpper();
					foreach (string mg in AllowedModules) 
					{
						if ( guidsInUse.IndexOf(mg.ToUpper()) > -1 ) 
                            return;
					}
				}
                if ( PageTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]StdAuxPage ModuleGuidInCookie AccessDenied ModuleID : {0}, guidsInUse : {1}", aModuleID, guidsInUse),PageTraceSwitch.Sw.Info);
				PortalSecurity.AccessDenied();
			}
		}

        #endregion overrides from ADNPage

        #region Ctors

        /// <summary>
        /// This Ctor set Update,cancel,SaveAndClose to true, Delete to false 
        /// </summary>
        protected StdAuxPage() 
        {}

        protected StdAuxPage(bool HasUpd,bool HasCancel,bool HasSaveClose,bool HasDelete) 
        {
            PageHasUpdateBtn        =   HasUpd;
            PageHasCancelBtn        =   HasCancel;
            PageHasSaveAndCloseBtn  =   HasSaveClose;
            PageHasDeleteBtn        =   HasDelete;
        }


        #endregion Ctors

        #region OnPrerender override

        // If the module contains an editor with potential translation module, add necessary goggle scripts
        protected override void OnPreRender(EventArgs e)
        {
            if ( !FastLoadPage && HasGoogleTranslator && !IsInAsyncPostBack )
            {
                string gPath    =   (Request.IsSecureConnection) ? "https://www.google.com/jsapi":"http://www.google.com/jsapi";
                RegisterADNClientScriptInclude("GoggleAPI", gPath);
                gPath           =   AddonNice.Settings.Path.ToAbsolute(Config.PortalScriptsPath + "/GoggleTranslator.js");
                RegisterADNClientScriptInclude("GoggleTranslator", gPath);
            }
            base.OnPreRender(e);
        }

        #endregion OnPrerender override

        #region PreInit Phase
        /// <summary>
        /// Here we create the command buttons and add them to the PlaceHolders prepared
        /// </summary>
		override protected void OnPreInit(EventArgs e)
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnPreInit Begin PageHasUpdateBtn: {0}, PageHasCancelBtn: {1}, PageHasSaveAndCloseBtn: {2}, PageHasDeleteBtn: {3}",
                    new object[]{PageHasUpdateBtn,PageHasCancelBtn,PageHasSaveAndCloseBtn,PageHasDeleteBtn}),PageTraceSwitch.Sw.Info);

            // Try to set masterPage if supported
            if ( !FastLoadPage && SupportMasterPage )
            {
                string strMasterPF      =   Settings[StStr.PageMasterPageFile].Value;
                if ( string.IsNullOrEmpty(strMasterPF) )
                        strMasterPF      =   portalSettings.MasterPageFile;
                if ( !string.IsNullOrEmpty(strMasterPF) && string.IsNullOrEmpty(base.MasterPageFile))
                {
                    MasterPageFile      =   strMasterPF;
                    if ( MasterPageTraceSwitch.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage OnPreInit : {0}", MasterPageFile),MasterPageTraceSwitch.Sw.Info);
                }
            }
            if ( !FastLoadPage )
            {
                if (PageHasUpdateBtn)
                {
                    updateButton        =   new ImageButton();
                    updateButton2       =   new ImageButton();
                }
                if (PageHasCancelBtn)
                {
                    cancelButton        =   new ImageButton();
                    cancelButton2       =   new ImageButton();
                }

                if (PageHasSaveAndCloseBtn)
                {
                    saveAndCloseButton  =   new ImageButton();
                    saveAndCloseButton2 =   new ImageButton();
                }
                if (PageHasDeleteBtn)
                {
                    deleteButton        =   new ImageButton();
                    deleteButton2       =   new ImageButton();
                }
            }
            base.OnPreInit(e);
            if ( PageTraceSwitch.Sw.TraceVerbose )
    			Trace2.WriteLine("[V]StdAuxPage OnPreInit End",PageTraceSwitch.Sw.Info);
        }


        #endregion PreInit Phase

        #region Init Phase

        protected override void OnInit(EventArgs e)
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]StdAuxPage OnInit Beg",PageTraceSwitch.Sw.Info);
            if ( !FastLoadPage )
            {
                InitializeComponent();
                InitButtons();
            }
			base.OnInit(e);
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]StdAuxPage OnInit End",PageTraceSwitch.Sw.Info);
        }

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent() 
		{    
            // mandatory because buttons included in a ContentPlaceHolder loose their Id and FindControl is unable to find them
            // so Page can't automatically find theses buttons based on their normal IDs
            //placeholders are not available in OnPreInit, we must add buttons to theme here
            if (placeHolderForButtons != null)
            {
                if (PageHasUpdateBtn)
                {
                    placeHolderForButtons.Controls.Add(updateButton);
                    if ( PageHasSaveAndCloseBtn || PageHasCancelBtn || PageHasDeleteBtn )
                        placeHolderForButtons.Controls.Add(new LiteralControl("&#160;"));
                }
                if (PageHasSaveAndCloseBtn)
                {
                    placeHolderForButtons.Controls.Add(saveAndCloseButton);
                    if ( PageHasCancelBtn || PageHasDeleteBtn )
                        placeHolderForButtons.Controls.Add(new LiteralControl("&#160;"));
                }
                if (PageHasCancelBtn)
                {
                    placeHolderForButtons.Controls.Add(cancelButton);
                    if ( PageHasDeleteBtn )
                        placeHolderForButtons.Controls.Add(new LiteralControl("&#160;"));
                }
                if (PageHasDeleteBtn)
                    placeHolderForButtons.Controls.Add(deleteButton);
            }

            if ( placeHolderForButtons2 != null )
            {
                if (PageHasUpdateBtn)
                {
                    placeHolderForButtons2.Controls.Add(updateButton2);
                    if ( PageHasSaveAndCloseBtn || PageHasCancelBtn || PageHasDeleteBtn )
                        placeHolderForButtons2.Controls.Add(new LiteralControl("&#160;"));
                }
                if (PageHasSaveAndCloseBtn)
                {
                    placeHolderForButtons2.Controls.Add(saveAndCloseButton2);
                    if ( PageHasCancelBtn || PageHasDeleteBtn )
                        placeHolderForButtons2.Controls.Add(new LiteralControl("&#160;"));
                }
                if (PageHasCancelBtn)
                {
                    placeHolderForButtons2.Controls.Add(cancelButton2);
                    if ( PageHasDeleteBtn )
                        placeHolderForButtons2.Controls.Add(new LiteralControl("&#160;"));
                }
                if (PageHasDeleteBtn)
                    placeHolderForButtons2.Controls.Add(deleteButton2);
            }
            // install demo limited version reporting
            // t allows signaling that current lcense is a demo one
            if ( SignalDemoLbl != null )
            {
                SignalDemo +=   new PageEventHandler(StdAuxPage_SignalDemo);
            }
        }

        /// <summary>
        /// Internal usage, assign text, validation, events, class to existing standard buttons
        /// </summary>
		protected virtual void InitButtons()
        {
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage InitButtons BEG Theme : {0}", Theme),PageTraceSwitch.Sw.Info);
            string btnText                                  =   string.Empty;
            WebControl iButton                              =   saveAndCloseButton;
            if (iButton != null)
            {
                btnText                                     =   LocalizeHelper.Localize("SAVE_AND_CLOSE", "Save and close");
                iButton.ToolTip                             =   btnText;
                if (iButton is LinkButton)
                {
                    ((LinkButton)iButton).Click             +=  new EventHandler(SaveAndCloseBtn_Click);
                    ((LinkButton)iButton).Text              =   btnText;
                    ((LinkButton)iButton).CausesValidation  =   false;
                }
                else if (iButton is Button)
                {
                    ((Button)iButton).Click                 +=  new EventHandler(SaveAndCloseBtn_Click);
                    ((Button)iButton).Text                  =   btnText;
                    ((Button)iButton).CausesValidation      =   false;
                }
                else if (iButton is ImageButton)
                {
                    ((ImageButton)iButton).Click            +=  new ImageClickEventHandler(SaveAndCloseImgBtn_Click);
                    ((ImageButton)iButton).AlternateText    =  btnText;
                    ((ImageButton)iButton).CausesValidation =   false;
                }
				if ( string.IsNullOrEmpty(iButton.SkinID) )
					iButton.CssClass                        =   "CommandButton";
                iButton.EnableViewState                     =   false;
                AddToolTipTarget(iButton.ClientID,true,TootipPos.Bottom);
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]StdAuxPage InitButtons saveAndCloseButton END.",PageTraceSwitch.Sw.Info);
            }

            iButton                                         =   saveAndCloseButton2;
            if (iButton != null)
            {
                iButton.ToolTip                             =   btnText;
                if (iButton is LinkButton)
                {
                    ((LinkButton)iButton).Click             +=  new EventHandler(SaveAndCloseBtn_Click);
                    ((LinkButton)iButton).Text              =   btnText;
                    ((LinkButton)iButton).CausesValidation  =   false;
                }
                else if (iButton is Button)
                {
                    ((Button)iButton).Click                 +=  new EventHandler(SaveAndCloseBtn_Click);
                    ((Button)iButton).Text                  =   btnText;
                    ((Button)iButton).CausesValidation      =   false;
                }
                else if (iButton is ImageButton)
                {
                    ((ImageButton)iButton).Click            +=  new ImageClickEventHandler(SaveAndCloseImgBtn_Click);
                    ((ImageButton)iButton).AlternateText    =   btnText;
                    ((ImageButton)iButton).CausesValidation =   false;
                }
				if ( string.IsNullOrEmpty(iButton.SkinID) )
					iButton.CssClass                        =   "CommandButton";
				iButton.EnableViewState                     =   false;
                AddToolTipTarget(iButton.ClientID,true,TootipPos.Top);
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]StdAuxPage InitButtons saveAndCloseButton2 END.",PageTraceSwitch.Sw.Info);
            }

            iButton                                         =   adminPropertiesButton;
            if (iButton != null)
            {
                btnText                                     =   LocalizeHelper.Localize("MODULESETTINGS_BASE_SETTINGS", "Edit base settings");
                iButton.ToolTip                             =   btnText;
				if (iButton is HyperLink)
				{
					HyperLink hButton                       =   (HyperLink)adminPropertiesButton;
					hButton.Text                            =   btnText;	
				}
				else if (iButton is LinkButton)
                {
                    ((LinkButton)iButton).Click             +=  new EventHandler(adminPropertiesBtn_Click);
                    ((LinkButton)iButton).Text              =   btnText;
                    ((LinkButton)iButton).CausesValidation  =   false;
                }
                else if (iButton is Button)
                {
                    ((Button)iButton).Click                 +=  new EventHandler(adminPropertiesBtn_Click);
                    ((Button)iButton).Text                  =   btnText;
                    ((Button)iButton).CausesValidation      =   false;
                }
                else if (iButton is ImageButton)
                {
                    ((ImageButton)iButton).Click            +=  new ImageClickEventHandler(adminPropertiesImgBtn_Click);
                    ((ImageButton)iButton).AlternateText    =   btnText;
                    ((ImageButton)iButton).CausesValidation =   false;
                }
				if ( string.IsNullOrEmpty(iButton.SkinID) )
					iButton.CssClass                        =   "CommandButton";
				iButton.EnableViewState                     =   false;
                AddToolTipTarget(iButton.ClientID,true,TootipPos.Bottom);
				if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]StdAuxPage InitButtons adminPropertiesButton END.",PageTraceSwitch.Sw.Info);
	           }

			iButton                                         =   adminPropertiesButton2;
            if (iButton != null)
            {
                iButton.ToolTip                             =   btnText;
				if (iButton is HyperLink)
				{
					HyperLink hButton                       =   (HyperLink)adminPropertiesButton2;
					hButton.Text                            =   btnText;
				}

				else if (iButton is LinkButton)
                {
                    ((LinkButton)iButton).Click             +=  new EventHandler(adminPropertiesBtn_Click);
                    ((LinkButton)iButton).Text              =   btnText;
                    ((LinkButton)iButton).CausesValidation  =   false;
                }
                else if (iButton is Button)
                {
                    ((Button)iButton).Click                 +=  new EventHandler(adminPropertiesBtn_Click);
                    ((Button)iButton).Text                  =   btnText;
                    ((Button)iButton).CausesValidation      =   false;
                }
                else if (iButton is ImageButton)
                {
                    ((ImageButton)iButton).Click            +=  new ImageClickEventHandler(adminPropertiesImgBtn_Click);
                    ((ImageButton)iButton).AlternateText    =   btnText;
                    ((ImageButton)iButton).CausesValidation =   false;
                }
				if ( string.IsNullOrEmpty(iButton.SkinID) )
					iButton.CssClass                        =   "CommandButton";
				iButton.EnableViewState                     =   false;
                AddToolTipTarget(iButton.ClientID,true,TootipPos.Top);
				if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]StdAuxPage InitButtons adminPropertiesButton2 END.",PageTraceSwitch.Sw.Info);
	           }

            iButton                                         =   cancelButton;
            if (iButton != null)
            {
                btnText                                     =   LocalizeHelper.Localize("CANCEL", "Cancel");
                iButton.ToolTip                             =   btnText;
                if (iButton is LinkButton)
                {
                    ((LinkButton)iButton).Click             +=  new EventHandler(CancelBtn_Click);
                    ((LinkButton)iButton).Text              =   btnText;
                    ((LinkButton)iButton).CausesValidation  =   false;
                }
                else if (iButton is Button)
                {
                    ((Button)iButton).Click                 +=  new EventHandler(CancelBtn_Click);
                    ((Button)iButton).Text                  =   btnText;
                    ((Button)iButton).CausesValidation      =   false;
                }
                else if (iButton is ImageButton)
                {
                    ((ImageButton)iButton).Click            +=  new ImageClickEventHandler(CancelImgBtn_Click);
                    ((ImageButton)iButton).AlternateText    =   btnText;
                    ((ImageButton)iButton).CausesValidation =   false;
                }
				if ( string.IsNullOrEmpty(iButton.SkinID) )
					iButton.CssClass                        =   "CommandButton";
                iButton.EnableViewState                     =   false;
                AddToolTipTarget(iButton.ClientID,true,TootipPos.Bottom);
                if ( HasCancelExtender )
                {
                    string msg                              =   LocalizeHelper.Localize("CONFIRM_CANCEL", "Confirm cancel");
                    string title                            =   LocalizeHelper.Localize("CANCEL", "Cancel");
                    setClientConfirmAttributes(iButton,msg,title);
                }
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]StdAuxPage InitButtons cancelButton END.",PageTraceSwitch.Sw.Info);
            }
            iButton                                         =   cancelButton2;
            if (iButton != null)
            {
                iButton.ToolTip                             =   btnText;
                if (iButton is LinkButton)
                {
                    ((LinkButton)iButton).Click             +=  new EventHandler(CancelBtn_Click);
                    ((LinkButton)iButton).Text              =   btnText;
                    ((LinkButton)iButton).CausesValidation  =   false;
                }
                else if (iButton is Button)
                {
                    ((Button)iButton).Click                 +=  new EventHandler(CancelBtn_Click);
                    ((Button)iButton).Text                  =   btnText;
                    ((Button)iButton).CausesValidation      =   false;
                }
                else if (iButton is ImageButton)
                {
                    ((ImageButton)iButton).Click            +=  new ImageClickEventHandler(CancelImgBtn_Click);
                    ((ImageButton)iButton).AlternateText    =   btnText;
                    ((ImageButton)iButton).CausesValidation =   false;
                }
				if ( string.IsNullOrEmpty(iButton.SkinID) )
					iButton.CssClass                        =   "CommandButton";
                iButton.EnableViewState                     =   false;
                AddToolTipTarget(iButton.ClientID,true,TootipPos.Top);
                if ( HasCancelExtender )
                {
                    string msg                              =   LocalizeHelper.Localize("CONFIRM_CANCEL", "Confirm cancel");
                    string title                            =   LocalizeHelper.Localize("CANCEL", "Cancel");
                    setClientConfirmAttributes(iButton,msg,title);
                }
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]StdAuxPage InitButtons cancelButton2 END.",PageTraceSwitch.Sw.Info);
            }
            iButton                                         =   updateButton;
            if (iButton != null)
            {
                btnText                                     =   LocalizeHelper.Localize("APPLY", "Apply");
                iButton.ToolTip                             =   btnText;
                if (iButton is LinkButton)
                {
                    ((LinkButton)iButton).Click             +=  new EventHandler(UpdateBtn_Click);
                    ((LinkButton)iButton).Text              =   btnText;
                    ((LinkButton)iButton).CausesValidation  =   false;
                }
                else if (iButton is Button)
                {
                    ((Button)iButton).Click                 +=  new EventHandler(UpdateBtn_Click);
                    ((Button)iButton).Text                  =   btnText;
                    ((Button)iButton).CausesValidation      =   false;
                }
                else if (iButton is ImageButton)
                {
                    ((ImageButton)iButton).Click            +=  new ImageClickEventHandler(UpdateImgBtn_Click);
                    ((ImageButton)iButton).AlternateText    =   btnText;
                    ((ImageButton)iButton).CausesValidation =   false;
                }
				if ( string.IsNullOrEmpty(iButton.SkinID) )
					iButton.CssClass                        =   "CommandButton";
                iButton.EnableViewState                     =   false;
                AddToolTipTarget(iButton.ClientID,true,TootipPos.Bottom);
                if ( HasUpdateExtender )
                {
                    string msg                              =   LocalizeHelper.Localize("CONFIRM_UPDATE", "Confirm update");
                    string title                            =   LocalizeHelper.Localize("UPDATE", "Update");
                    setClientConfirmAttributes(iButton,msg,title);
                }
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]StdAuxPage InitButtons updateButton END.",PageTraceSwitch.Sw.Info);
            }
            iButton                                         =   updateButton2;
            if (iButton != null)
            {
                iButton.ToolTip                             =   btnText;
                if (iButton is LinkButton)
                {
                    ((LinkButton)iButton).Click             +=  new EventHandler(UpdateBtn_Click);
                    ((LinkButton)iButton).Text              =   btnText;
                    ((LinkButton)iButton).CausesValidation  =   false;
                }
                else if (iButton is Button)
                {
                    ((Button)iButton).Click                 +=  new EventHandler(UpdateBtn_Click);
                    ((Button)iButton).Text                  =   btnText;
                    ((Button)iButton).CausesValidation      =   false;
                }
                else if (iButton is ImageButton)
                {
                    ((ImageButton)iButton).Click            +=  new ImageClickEventHandler(UpdateImgBtn_Click);
                    ((ImageButton)iButton).AlternateText    =   btnText;
                    ((ImageButton)iButton).CausesValidation =   false;
                }
				if ( string.IsNullOrEmpty(iButton.SkinID) )
					iButton.CssClass                        =   "CommandButton";
                iButton.EnableViewState                     =   false;
                AddToolTipTarget(iButton.ClientID,true,TootipPos.Top);
                if ( HasUpdateExtender )
                {
                    string msg                              =   LocalizeHelper.Localize("CONFIRM_UPDATE", "Confirm update");
                    string title                            =   LocalizeHelper.Localize("UPDATE", "Update");
                    setClientConfirmAttributes(iButton,msg,title);
                }
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]StdAuxPage InitButtons updateButton2 END.",PageTraceSwitch.Sw.Info);
            }
            iButton                                         =   deleteButton;
            if (iButton != null)
            {
                btnText                                     =   LocalizeHelper.Localize("DELETE", "Delete");
                iButton.ToolTip                             =   btnText;
                if (iButton is LinkButton)
                {
                    ((LinkButton)iButton).Click             +=  new EventHandler(DeleteBtn_Click);
                    ((LinkButton)iButton).Text              =   btnText;
                    ((LinkButton)iButton).CausesValidation  =   false;
                }
                else if (iButton is Button)
                {
                    ((Button)iButton).Click                 +=  new EventHandler(DeleteBtn_Click);
                    ((Button)iButton).Text                  =   btnText;
                    ((Button)iButton).CausesValidation      =   false;
                }
                else if (iButton is ImageButton)
                {
                    ((ImageButton)iButton).Click            +=  new ImageClickEventHandler(DeleteImgBtn_Click);
                    ((ImageButton)iButton).AlternateText    =   btnText;
                    ((ImageButton)iButton).CausesValidation =   false;
                }
				if ( string.IsNullOrEmpty(iButton.SkinID) )
					iButton.CssClass                        =   "CommandButton";
                iButton.EnableViewState                     =   false;
                AddToolTipTarget(iButton.ClientID,true,TootipPos.Bottom);
                // Assign current permissions to Delete button
                if ( IsUnderCRM && !string.IsNullOrEmpty(EntityName) && !PortalSecurity.HasDeletePermissions(EntityName))
                {
                    iButton.Visible                         =   false;
                }
                else if ( HasDeleteExtender )
                {
                    string msg                              =   LocalizeHelper.Localize("CONFIRM_DELETE", "Confirm Delete");
                    string title                            =   LocalizeHelper.Localize("DELETE", "Delete");
                    setClientConfirmAttributes(iButton,msg,title);
                }
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]StdAuxPage InitButtons deleteButton END.",PageTraceSwitch.Sw.Info);
            }
            iButton                                         =   deleteButton2;
            if (iButton != null)
            {
                iButton.ToolTip                             =   btnText;
                if (iButton is LinkButton)
                {
                    ((LinkButton)iButton).Click             +=  new EventHandler(DeleteBtn_Click);
                    ((LinkButton)iButton).Text              =   btnText;
                    ((LinkButton)iButton).CausesValidation  =   false;
                }
                else if (iButton is Button)
                {
                    ((Button)iButton).Click                 +=  new EventHandler(DeleteBtn_Click);
                    ((Button)iButton).Text                  =   btnText;
                    ((Button)iButton).CausesValidation      =   false;
                }
                else if (iButton is ImageButton)
                {
                    ((ImageButton)iButton).Click            +=  new ImageClickEventHandler(DeleteImgBtn_Click);
                    ((ImageButton)iButton).AlternateText    =   btnText;
                    ((ImageButton)iButton).CausesValidation =   false;
                }
				if ( string.IsNullOrEmpty(iButton.SkinID) )
					iButton.CssClass                        =   "CommandButton";
                iButton.EnableViewState                     =   false;
                AddToolTipTarget(iButton.ClientID,true,TootipPos.Top);
                // Assign current permissions to Delete button
                if (IsUnderCRM && !string.IsNullOrEmpty(EntityName) && !PortalSecurity.HasDeletePermissions(EntityName))
                {
                    iButton.Visible                         =   false;
                }
                else if ( HasDeleteExtender )
                {
                    string msg                              =   LocalizeHelper.Localize("CONFIRM_DELETE", "Confirm Delete");
                    string title                            =   LocalizeHelper.Localize("DELETE", "Delete");
                    setClientConfirmAttributes(iButton,msg,title);
                }
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]StdAuxPage InitButtons deleteButton2 END.",PageTraceSwitch.Sw.Info);
            }
            
            iButton                                         =   customButton;
            if (iButton != null)
            {
                btnText                                     =   LocalizeHelper.Localize(CustomBtnName, CustomBtnName);
                iButton.ToolTip                             =   btnText;
                if (iButton is LinkButton)
                {
                    ((LinkButton)iButton).Click             +=  new EventHandler(CustomBtn_Click);
                    ((LinkButton)iButton).Text              =   btnText;
                    ((LinkButton)iButton).CausesValidation  =   false;
                }
                else if (iButton is Button)
                {
                    ((Button)iButton).Click                 +=  new EventHandler(CustomBtn_Click);
                    ((Button)iButton).Text                  =   btnText;
                    ((Button)iButton).CausesValidation      =   false;
                }
                else if (iButton is ImageButton)
                {
                    ((ImageButton)iButton).Click            +=  new ImageClickEventHandler(CustomImgBtn_Click);
                    ((ImageButton)iButton).AlternateText    =   btnText;
                    ((ImageButton)iButton).CausesValidation =   false;
                }
				if ( string.IsNullOrEmpty(iButton.SkinID) )
					iButton.CssClass                        =   "CommandButton";
                iButton.EnableViewState                     =   false;
                AddToolTipTarget(iButton.ClientID,true,TootipPos.Bottom);
                if (HasCustomExtender)
                {
                    string msg                              =   LocalizeHelper.Localize("CONFIRM_" + CustomBtnName.ToUpper(), "Confirm " + CustomBtnName);
                    string title                            =   LocalizeHelper.Localize("CONFIRM_" + CustomBtnName.ToUpper(), "Confirm " + CustomBtnName);
                    setClientConfirmAttributes(iButton,msg,title);
                }
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]StdAuxPage InitButtons customButton END.",PageTraceSwitch.Sw.Info);
            }
            iButton                                         =   customButton2;
            if (iButton != null)
            {
                iButton.ToolTip                             =   btnText;
                if (iButton is LinkButton)
                {
                    ((LinkButton)iButton).Click             +=  new EventHandler(CustomBtn_Click);
                    ((LinkButton)iButton).Text              =   btnText;
                    ((LinkButton)iButton).CausesValidation  =   false;
                }
                else if (iButton is Button)
                {
                    ((Button)iButton).Click                 +=  new EventHandler(CustomBtn_Click);
                    ((Button)iButton).Text                  =   btnText;
                    ((Button)iButton).CausesValidation      =   false;
                }
                else if (iButton is ImageButton)
                {
                    ((ImageButton)iButton).Click            +=  new ImageClickEventHandler(CustomImgBtn_Click);
                    ((ImageButton)iButton).AlternateText    =   btnText;
                    ((ImageButton)iButton).CausesValidation =   false;
                }
				if ( string.IsNullOrEmpty(iButton.SkinID) )
					iButton.CssClass                        =   "CommandButton";
                iButton.EnableViewState                     =   false;
                AddToolTipTarget(iButton.ClientID,true,TootipPos.Top);
                if ( HasCustomExtender )
                {
                    string msg                              =   LocalizeHelper.Localize("CONFIRM_" + CustomBtnName.ToUpper(), "Confirm " + CustomBtnName);
                    string title                            =   LocalizeHelper.Localize("CONFIRM_" + CustomBtnName.ToUpper(), "Confirm " + CustomBtnName);
                    setClientConfirmAttributes(iButton,msg,title);
                }
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]StdAuxPage InitButtons customButton2 END.",PageTraceSwitch.Sw.Info);
            }
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]StdAuxPage InitButtons END.",PageTraceSwitch.Sw.Info);
        }

       #endregion Init Phase
    }
}